import {onMounted, ref, onBeforeUnmount, toRefs, watch} from 'vue'
import skin_layout from "@/components/Player/js/skin_layout";
import player_components from "@/components/Player/js/player_components";


//用于生成播放器对象
export default function generator_player(vid, play_auth, context) {
    const player = ref(null)
    const player_id = ref('id_' + Math.round(Math.random() * 10000000 * 10000000))
    //生成播放器对象
    const generator = () => {
        player.value = new Aliplayer({
            isLive: true,//是否为直播
            id: player_id.value,
            width: '100%',
            autoplay: true,//自动播放
            defaultDefinition: "SD",//默认清晰度
            source: !play_auth.value ? vid.value : null,//没有传入play_auth时用vid当作视频源
            keyShortCuts: true,//快捷键 方向键（左右键）控制快进和快退，方向键（上下键）控制音量的增减，空格键暂停和播放。
            skinLayout: skin_layout,//皮肤
            components: player_components,//组件
            vid: vid.value,//音视频ID。示例：1e067a2831b641db90d570b6480f****。
            playauth: play_auth.value
        }, function (player) {
            console.log('player created')

        });
        context.emit('update:player', player)//将生成的播放器对象双向绑定给父组件
    }
    //播放地址发生变化重新生成一个播放器
    watch(vid, () => {
        if (player.value) {//在生成新的播放器之前消费之前的播放器
            // console.log('player dispose')
            player.value.dispose()
        }
        generator()
        // console.log('watch generator')
    })
    onMounted(generator)
    onBeforeUnmount(() => {
        player.value.dispose(); //销毁播放器
        // console.log('player dispose')
    })
    return {
        player,
        player_id
    }
}